package com.sxm.yiwei.activitis;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.view.ContextThemeWrapper;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.animation.RotateAnimation;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.sxm.yiwei.R;
import com.sxm.yiwei.tools.CropPictures;
import com.sxm.yiwei.utils.InternetAddressUtis;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

public class HopeActivity extends BaseActivity implements View.OnClickListener{

    private ImageView hopeImg;
    private File mCurrentPhotoFile;
    private static final int PHOTO_PICKED_WITH_DATA = 3021;
    /*用来标识请求照相功能的activity*/
    private static final int CAMERA_WITH_DATA = 3023;
    private static final File PHOTO_DIR = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera");
    private ArrayList<String> mList = new ArrayList<String>();

    private ImageView hopechenged;
    private Bitmap photo;
    private EditText hopetext;
    private static final  int PHOTO_TEXT= 3022;
    private String path1;
    private int index ;
    private String imgurl;
    private String s;
    private TextView hopex;
    private String imgpath;
    private TextView backt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hope);
        initHopeView();
    }

    private void initHopeView() {
        hopeImg = (ImageView) findViewById(R.id.hopeimg);
        hopetext = (EditText) findViewById(R.id.hope_inputtext);
        hopechenged = (ImageView) findViewById(R.id.hope_chenged);
        hopex = (TextView) findViewById(R.id.hope_x);
        backt = (TextView) findViewById(R.id.hope_backt);
        hopex.setOnClickListener(this);
        backt.setOnClickListener(this);
        hopeImg.setOnClickListener(this);
        hopechenged.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.hope_backt:
                finish();
                break;
            case R.id.hopeimg:
                doPickPhotoAction();
                break;
            case R.id.hope_x:
                Intent i = new Intent(HopeActivity.this,WEBXActivity.class);
                i.putExtra("from","hope");
                i.putExtra("url", InternetAddressUtis.XHOPE);
                startActivity(i);
                break;
            case R.id.hope_chenged:
                //startActivity(new Intent(this,HopeSengActivity.class));
                if (imgpath==null){
                    Toast.makeText(this, "请补全你得图片", Toast.LENGTH_SHORT).show();
                }else {
                    Intent intent = new Intent(HopeActivity.this,HopeSengActivity.class);
                    intent.putExtra("photo",photo);
                    intent.putExtra("text",hopetext.getText().toString());
                    intent.putExtra("imgurl",imgpath);
                    startActivity(intent);
                    finish();
                }
                break;
        }
    }
    private void doPickPhotoAction() {
        final Context context = this;
        AlertDialog.Builder b1 = new AlertDialog.Builder(context);
        View view = LayoutInflater.from(context).inflate(R.layout.picture_dialog, null);
        b1.setView(view);

        TextView camere = (TextView) view.findViewById(R.id.picdia_camere);
        TextView pic = (TextView) view.findViewById(R.id.picdia_pic);
        TextView cancel1 = (TextView) view.findViewById(R.id.picdia_cancel);

        final AlertDialog dialog1 = b1.create();
        Window window = dialog1.getWindow();
        camere.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String status= Environment.getExternalStorageState();
                if(status.equals(Environment.MEDIA_MOUNTED)){//判断是否有SD卡
                    // index=0;
                    doTakePhoto();// 用户点击了从照相机获取
                    dialog1.dismiss();
                }
                else{
                    Toast.makeText(context, "没有SD卡", Toast.LENGTH_SHORT).show();
                }
            }
        });
        pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doPickPhotoFromGallery();// 从相册中去获取
                dialog1.dismiss();
            }
        });
        cancel1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog1.dismiss();
            }
        });
        dialog1.show();
        window.setGravity(Gravity.BOTTOM);
    }
    /**
     * 拍照获取图片
     *
     */
    protected void doTakePhoto() {
        try {
            // Launch camera to take photo for selected contact
            PHOTO_DIR.mkdirs();// 创建照片的存储目录
            // 给新照的照片文件命名
            mCurrentPhotoFile = new File(PHOTO_DIR, getPhotoFileName());
            final Intent intent = getTakePickIntent(mCurrentPhotoFile);
            startActivityForResult(intent, CAMERA_WITH_DATA);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, R.string.photoPickerNotFoundText,
                    Toast.LENGTH_LONG).show();
        }
    }

    public Intent getTakePickIntent(File f) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri uri11 = FileProvider.getUriForFile(HopeActivity.this, HopeActivity.this.getApplicationContext().getPackageName() + ".provider", f);
            intent.putExtra(MediaStore.EXTRA_OUTPUT,uri11);
            //  大于等于24即为7.0及以上执行内容
        } else {
            //  低于24即为7.0以下执行内容
            intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(f));
        }
        return intent;
    }

    /**
     * 用当前时间给取得的图片命名
     *
     */
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyyMMddHHmmss");
        return dateFormat.format(date) + ".jpg";
    }

    // 请求Gallery程序
    protected void doPickPhotoFromGallery() {
        try {
            // Launch picker to choose photo for selected contact
            final Intent intent = getPhotoPickIntent();
            startActivityForResult(intent, PHOTO_TEXT);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, R.string.photoPickerNotFoundText1,
                    Toast.LENGTH_LONG).show();
        }

    }

    // 封装请求Gallery的intent
    public static Intent getPhotoPickIntent() {

        Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
        return intent;

    }

    // 因为调用了Camera和Gally所以要判断他们各自的返回情况,他们启动时是这样的startActivityForResult
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的    byte---224676  171396 393128

                photo = data.getParcelableExtra("data");
                imgpath = CropPictures.saveBitmapFile(photo, getPhotoFileName());
                RotateAnimation animation = new RotateAnimation(0,-15,50,50);
                animation.setRepeatCount(1);
                animation.setFillAfter(true);
                animation.setDuration(1);
                hopeImg.setImageBitmap(photo);
                hopeImg.startAnimation(animation);
                break;
            }

            case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
                s = mCurrentPhotoFile.getAbsolutePath();
                doCropPhoto(mCurrentPhotoFile);

                break;
            }
            case PHOTO_TEXT:
               /* Uri data1 = data.getData();
                ContentResolver resolver = getContentResolver();
                try {
                    photo = MediaStore.Images.Media.getBitmap(resolver, data1);
                    String[] proj = {MediaStore.Images.Media.DATA};
                    Cursor cursor = managedQuery(data1, proj, null, null, null);
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    //图片路径
                    path1 = cursor.getString(column_index);
                    File file = new File(path1);
                    doCropPhoto(file);
                } catch (IOException e) {
                    e.printStackTrace();
                }*/
                Uri data1 = data.getData();
                if (!TextUtils.isEmpty(data1.getAuthority())){
                    ContentResolver resolver = getContentResolver();
                    try {
                        photo = MediaStore.Images.Media.getBitmap(resolver, data1);
                        String[] proj = {MediaStore.Images.Media.DATA};
                        Cursor cursor = managedQuery(data1, proj, null, null, null);
                        if (cursor==null){
                            Toast.makeText(this, "没有找到图片", Toast.LENGTH_SHORT).show();
                        }else {
                            cursor.moveToFirst();
                            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                            //图片路径
                            path1 = cursor.getString(column_index);

                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    path1 = data1.getPath();
                }
                File file = new File(path1);
                doCropPhoto(file);
                break;

        }

    }

    protected void doCropPhoto(File f) {
        try {
            // 启动gallery去剪辑这个照片
            final Intent intent;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri uriForFile = FileProvider.getUriForFile(HopeActivity.this, HopeActivity.this.getApplicationContext().getPackageName() + ".provider", f);
                intent = getCropImageIntent(uriForFile);

                //  大于等于24即为7.0及以上执行内容
            } else {
                //  低于24即为7.0以下执行内容
                intent = getCropImageIntent(Uri.fromFile(f));

            }
            startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
        } catch (Exception e) {
            Toast.makeText(this, R.string.photoPickerNotFoundText,
                    Toast.LENGTH_LONG).show();
        }
    }

    /**
     * Constructs an intent for image cropping. 调用图片剪辑程序
     */
    public static Intent getCropImageIntent(Uri photoUri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(photoUri, "image/*");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 400);
        intent.putExtra("outputY", 480);
        intent.putExtra("return-data", true);
        return intent;
    }
}
